<template>
  <div class="ep-container">
    <el-form-item :label="options.label" :prop="options.name" :show-message="!isDetail" class="ep-form-item">
      <div class="ep-correlation-container">
        <transition-group tag="ul" class="correlation-list" name="list">
          <li v-for="(obj, i) in fieldModel" :key="i" class="correlation-item" :tabindex="i">
            <slot :item="obj" :remove="() => fieldModel.splice(i, 1)">
              <!-- <span v-show="!designer">请在表单组件中使用correlation插槽</span> -->
            </slot>
          </li>
        </transition-group>
        <div v-if="!isDetail" class="ep-footer">
          <slot name="btn">
            <el-button plain @click="dialogVisible = true">
              <template #icon>
                <Plus />
              </template>
              添加审批
            </el-button>
          </slot>
          <slot name="tip">
            <div v-if="options.tip" class="ep-correlation__tip">
              {{ options.tip }}
            </div>
          </slot>
        </div>
      </div>
    </el-form-item>
    <el-dialog v-model="dialogVisible" title="选择关联审批" class="correlation-dialog" append-to-body>
      <slot name="dialog" :options="options" :callback="onCallback">
        <!-- <span v-show="!designer">请在表单组件中使用correlation-dialog插槽</span> -->
      </slot>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="onSave"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import { defineComponent, computed, ref, getCurrentInstance, watch } from 'vue'
import defaultProps from '../props'

const name = 'ep-correlation'
Symbol(name)

export default defineComponent({
  name,
  props: defaultProps,
  emits: ['update:modelValue'],
  setup(props, { emit }) {
    const instance = getCurrentInstance()
    const proxy = instance?.proxy
    const isDetail = computed(() => props.options.permission > 0)
    const fieldModel = computed({
      get() {
        return props.modelValue as Array<any>
      },
      set(val: Array<any>) {
        emit('update:modelValue', val)
      }
    })
    const dialogVisible = ref(false)

    /** 初始化 */
    watch(dialogVisible, (val) => {
      if (val) {
        list = props.modelValue || []
      }
    })

    let list = props.modelValue || []
    const onCallback = (e: any) => {
      list = [...e]
    }

    const onSave = () => {
      const { limit, tip } = props.options
      if (list.length > limit) {
        proxy?.$message.error(tip || '超出最多关联数量')
        return false
      }
      dialogVisible.value = false
      emit('update:modelValue', list)
    }

    return {
      fieldModel,
      isDetail,
      dialogVisible,
      onCallback,
      onSave
    }
  }
})
</script>
